package com.zy.explore.wechat.controller.v1;

import com.alibaba.fastjson.JSON;
import com.jfinal.weixin.sdk.encrypt.AesException;
import com.zy.explore.wechat.util.WechatSignUtil;
import com.zy.explore.wechat.frm.WXMessgeBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringWriter;

/**
 * description 微信授权控制器
 *
 * @author ZY
 * @date 2021年05月24日 19:53
 */
@Slf4j
@RestController
@RequestMapping("/wx")
public class WxAuthController {

    @Value("${wechat.valid.token:ZW9mhz4gx6AOzWgNUB9LjxvmJbNGg4th}")
    private String token;

    @Value("${wechat.valid.encodingAESKey:bCCs0quECaSM3o7F7UDjAbsSlbx7YQPwID7z6hR1GMK}")
    private String encodingAESKey;

    @Value("${wechat.valid.appId:wx137337c40f1313b5}")
    private String appId;

    @PostMapping("/authValidate")
    public String authValidate(HttpServletRequest request) throws AesException {

        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机数
        String echostr = request.getParameter("echostr");

//        String msgSignature = request.getParameter("msg_signature");
//        String postData = request.getParameter("postData");

        log.info("微信验证服务器入参：signature={}，timestamp={}，nonce={}，echostr={}", signature, timestamp, nonce, echostr);
        boolean bool = WechatSignUtil.checkSignature(token, signature, timestamp, nonce);
        if (!bool) {
            log.info("签名验证不通过，非微信消息");
            return "check fail";
        }
        try {
            Marshaller marshaller;
            Unmarshaller unmarshal;
            // 你要解析成哪个bean对象，newInstance的参数就是哪个对象
            JAXBContext jaxbContext = JAXBContext.newInstance(WXMessgeBean.class);
            unmarshal = jaxbContext.createUnmarshaller();
            // xml解码成bean对象
            WXMessgeBean wxMessgeBean = (WXMessgeBean) unmarshal.unmarshal(request.getInputStream());
            if ("text".equals(wxMessgeBean.getMsgType())){
                System.out.println(JSON.toJSONString(wxMessgeBean));
                WXMessgeBean bean = new WXMessgeBean();
                bean.setFromUserName(wxMessgeBean.getToUserName());
                bean.setToUserName(wxMessgeBean.getFromUserName());
                bean.setCreateTime(System.currentTimeMillis());
                bean.setMsgType("text");
                bean.setContent("你好，欢迎浏览我的公众号");
                marshaller = jaxbContext.createMarshaller();
                StringWriter writer = new StringWriter();
                marshaller.marshal(bean,writer);
                return writer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return echostr;
    }

}
